import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../index.dart';
import 'review_detail_bottom_sheet.dart';
import '../../../../../common/api/comment_api.dart';
import '../../../../../common/services/user_service.dart';
import '../../../../../common/utils/toast_util.dart';
import 'dart:developer' as developer;
import 'dart:convert';

class CommentTab extends StatelessWidget {
  const CommentTab({Key? key}) : super(key: key);
  
  /// 处理评论点赞
  Future<void> _handleCommentLike(dynamic post) async {
    // 检查用户是否登录
    final userService = UserService.to;
    if (!userService.isLoggedIn) {
      ToastUtil.warning('请先登录');
      return;
    }
    
    // 获取评论ID
    int commentId;
    try {
      if (post.originalCommentId != null) {
        commentId = post.originalCommentId!;
      } else {
        // 从字符串ID中解析数字
        final idParts = post.id.split('_');
        if (idParts.length >= 3 && idParts[0] == 'real' && idParts[1] == 'comment') {
          commentId = int.parse(idParts[2]);
        } else {
          commentId = int.parse(post.id);
        }
      }
    } catch (e) {
      developer.log('❌ 评论ID格式错误: ${post.id}');
      ToastUtil.error('评论ID格式错误');
      return;
    }
    
    try {
      developer.log('');
      developer.log('👍 =============== 评论列表页点赞 ===============');
      developer.log('🎯 评论ID: $commentId');
      developer.log('👤 用户ID: ${userService.currentUser?.userid}');
      developer.log('📊 当前点赞数: ${post.likeCount}');
      
      // 显示加载提示
      ToastUtil.info('正在处理点赞...');
      
      // 调用点赞API
      final response = await CommentApi.likeComment(
        userId: userService.currentUser!.userid,
        commentId: commentId,
      );
      
      developer.log('📨 点赞API响应: ${jsonEncode(response)}');
      
      if (response['status'] == 'success') {
        final action = response['action'] ?? 'unknown';
        final pointsChange = response['pointsChange'] ?? 0;
        final message = response['message'] ?? '操作成功';
        
        // 🔥 不直接修改post对象，而是通过显示提示信息
        if (action == 'like') {
          ToastUtil.success('👍 $message');
        } else if (action == 'unlike') {
          ToastUtil.info('已取消点赞');
        } else {
          ToastUtil.success('👍 点赞成功');
        }
        
        if (pointsChange > 0) {
          developer.log('💰 获得积分: +$pointsChange');
          ToastUtil.info('获得积分: +$pointsChange');
          
          // 刷新用户积分信息
          userService.refreshUserInfo();
        }
        
        // 刷新评论列表以同步服务器状态
        try {
          final playsController = Get.find<PlaysController>();
          await playsController.refreshCommentData();
          developer.log('🔄 评论列表已刷新');
        } catch (e) {
          developer.log('⚠️ 刷新评论列表失败: $e');
        }
        
        developer.log('✅ 点赞操作成功');
        
      } else {
        // API调用失败
        final errorMsg = response['message'] ?? '点赞失败';
        developer.log('❌ 点赞操作失败: $errorMsg');
        
        if (errorMsg.contains('评论不存在') || errorMsg.contains('已删除')) {
          ToastUtil.error('💔 该评论已被删除');
        } else {
          ToastUtil.error('点赞失败: $errorMsg');
        }
      }
      
    } catch (e, stackTrace) {
      developer.log('💥 点赞操作异常: $e');
      developer.log('📍 异常堆栈: $stackTrace');
      ToastUtil.error('点赞异常: ${e.toString()}');
    } finally {
      developer.log('🏁 =============== 评论列表页点赞完成 ===============');
      developer.log('');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFF5F5F5), // 与AppBar背景色保持一致
      child: GetBuilder<PlaysController>(
        builder: (controller) => Obx(() => SmartRefresher(
          enablePullDown: true,              // ✅ 启用下拉刷新
          enablePullUp: true,                // ✅ 启用上拉加载
          header: _buildSimpleHeader(),
          footer: _buildCustomFooter(),      // 🎨 自定义底部样式
          controller: controller.commentRefreshController, // 🎮 控制器绑定
          onRefresh: controller.onCommentRefresh,   // ⬇️ 下拉刷新回调
          onLoading: controller.onCommentLoading,   // ⬆️ 上拉加载回调
          child: _buildContent(context, controller), // 🔥 构建内容
        )),
      ),
    );
  }

  /// 🏗️ 构建主内容
  Widget _buildContent(BuildContext context, PlaysController controller) {
    // 如果正在加载且没有数据，显示加载状态
    if (controller.isLoadingComments.value && controller.commentPosts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
            ),
            const SizedBox(height: 16),
            const Text(
              '正在加载评论数据...',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    // 使用CustomScrollView + SliverGrid实现流畅滚动
    return CustomScrollView(
      slivers: [
        // 顶部间距
        SliverToBoxAdapter(
          child: SizedBox(height: MediaQuery.of(context).padding.top + 10.h),
        ),
        
        // 主要内容 - SliverGrid
        SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 16.w,
              mainAxisSpacing: 16.h,
              childAspectRatio: 0.75, // 🎨 与activity_tab.dart保持一致的高度
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) => _buildCommentCard(controller.commentPosts[index]),
              childCount: controller.commentPosts.length,
            ),
          ),
        ),
        
        // 底部间距
        SliverToBoxAdapter(
          child: SizedBox(height: 16.h),
        ),
      ],
    );
  }

  /// 🎨 构建单个评论卡片
  Widget _buildCommentCard(dynamic post) {
    return GestureDetector(
      onTap: () {
        ReviewDetailBottomSheet.show(post: post);
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withValues(alpha: 0.1),
              blurRadius: 4.r,
              offset: Offset(0, 2.h),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 图片区域
            if (post.images.isNotEmpty)
              ClipRRect(
                borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
                child: AspectRatio(
                  aspectRatio: 1.2, // 🔥 统一使用1.2比例，避免拉伸
                  child: post.images.first.isNotEmpty && 
                         !post.images.first.contains('example.com')
                      ? CachedNetworkImage(
                          imageUrl: post.images.first,
                          fit: BoxFit.cover, // 🔥 保持比例填充，避免拉伸
                          width: double.infinity, // 🔥 确保图片填满容器宽度
                          height: double.infinity, // 🔥 确保高度也填满
                          placeholder: (context, url) => Container(
                            color: Colors.grey[50],
                            // 移除loading动画，直接显示空白背景
                          ),
                          errorWidget: (context, url, error) => Container(
                            color: Colors.grey[300],
                            child: const Icon(Icons.image_not_supported),
                          ),
                          // 🔥 修复：大幅提高缓存分辨率解决图片模糊问题
                          memCacheWidth: 800,  // 内存缓存宽度（大幅提升）
                          memCacheHeight: 800, // 内存缓存高度（大幅提升）
                          maxWidthDiskCache: 800, // 磁盘缓存最大宽度（大幅提升）
                          maxHeightDiskCache: 800, // 磁盘缓存最大高度（大幅提升）
                          // 🔥 优化图片质量设置
                          filterQuality: FilterQuality.high, // 使用高质量过滤
                          fadeInDuration: Duration.zero, // 禁用淡入动画提升性能
                          fadeOutDuration: Duration.zero, // 禁用淡出动画
                        )
                      : Container(
                          color: Colors.grey[100],
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.photo,
                                size: 24,
                                color: Colors.grey[400],
                              ),
                              const SizedBox(height: 2),
                              Text(
                                '暂无图片',
                                style: TextStyle(
                                  fontSize: 8,
                                  color: Colors.grey[500],
                                ),
                              ),
                            ],
                          ),
                        ),
                ),
              ),
            // 内容区域
            Padding(
              padding: EdgeInsets.all(6.r),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 标题
                  Text(
                    post.title,
                    style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 1.h),
                  // 内容
                  Text(
                    post.content,
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey[600],
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 2.h),
                  // 用户信息和点赞
                  Row(
                    children: [
                      // 用户头像
                      CircleAvatar(
                        radius: 6.r,
                        backgroundImage: post.authorAvatar.isNotEmpty
                            ? NetworkImage(post.authorAvatar)
                            : null,
                        onBackgroundImageError: (_, __) {},
                        child: post.authorAvatar.isEmpty 
                            ? const Icon(Icons.person, size: 10, color: Colors.grey)
                            : null,
                      ),
                      SizedBox(width: 3.w),
                      // 用户名和个性签名
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              post.authorName.isEmpty ? '未知用户' : post.authorName,
                              style: TextStyle(
                                fontSize: 9.sp,
                                color: Colors.grey[600],
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            if (post.authorSignature.isNotEmpty)
                              Text(
                                post.authorSignature,
                                style: TextStyle(
                                  fontSize: 7.sp,
                                  color: Colors.grey[400],
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                          ],
                        ),
                      ),
                      // 点赞按钮
                      GestureDetector(
                        onTap: () => _handleCommentLike(post),
                        child: Row(
                          children: [
                            Icon(
                              Icons.thumb_up_outlined,
                              size: 12.r,
                              color: Colors.grey[600],
                            ),
                            SizedBox(width: 2.w),
                            Text(
                              '${post.likeCount}',
                              style: TextStyle(
                                fontSize: 9.sp,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 🔧 备用方案：简单的自定义Header
  Widget _buildSimpleHeader() {
    return CustomHeader(
      builder: (BuildContext context, RefreshStatus? mode) {
        return Container(
          height: 60.0,
          color: const Color(0xFFF5F5F5),
          child: Center(
            child: _getHeaderWidget(mode),
          ),
        );
      },
    );
  }
  
  Widget _getHeaderWidget(RefreshStatus? mode) {
    switch (mode) {
      case RefreshStatus.idle:
        return const Text("下拉刷新", style: TextStyle(color: Colors.grey));
      case RefreshStatus.canRefresh:
        return const Text("松手刷新", style: TextStyle(color: Color(0xFFE33641)));
      case RefreshStatus.refreshing:
        return const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 20, height: 20,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
              ),
            ),
            SizedBox(width: 8),
            Text("刷新中...", style: TextStyle(color: Color(0xFFE33641))),
          ],
        );
      case RefreshStatus.completed:
        return const Text("刷新完成", style: TextStyle(color: Colors.green));
      case RefreshStatus.failed:
        return const Text("刷新失败", style: TextStyle(color: Colors.red));
      default:
        return const Text("下拉刷新", style: TextStyle(color: Colors.grey));
    }
  }

  /// 🎨 构建自定义Footer - 精美的加载状态显示
  Widget _buildCustomFooter() {
    return CustomFooter(
      builder: (BuildContext context, LoadStatus? mode) {
        Widget body;
        double height = 55.0;
        
        if (mode == LoadStatus.idle) {
          body = const Text(
            "上拉加载更多评论", 
            style: TextStyle(color: Colors.grey, fontSize: 14),
          );
        } else if (mode == LoadStatus.loading) {
          body = Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                ),
              ),
              SizedBox(width: 12),
              Text(
                "加载评论中...",
                style: TextStyle(color: Colors.grey, fontSize: 14),
              ),
            ],
          );
        } else if (mode == LoadStatus.failed) {
          body = const Text(
            "加载失败，点击重试",
            style: TextStyle(color: Colors.grey, fontSize: 14),
          );
        } else if (mode == LoadStatus.canLoading) {
          body = const Text(
            "松手加载更多评论",
            style: TextStyle(color: Colors.grey, fontSize: 14),
          );
        } else {
          // LoadStatus.noMore - 没有更多数据时的美化显示
          height = 80.0; // 增加高度让底部更美观
          body = Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 30,
                height: 1,
                color: Colors.grey[300],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.check_circle_outline,
                    size: 16,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(width: 6),
                  Text(
                    "已加载全部评论",
                    style: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 13,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
            ],
          );
        }
        
        return Container(
          height: height,
          alignment: Alignment.center,
          child: AnimatedSwitcher(
            duration: const Duration(milliseconds: 300),
            child: body,
          ),
        );
      },
    );
  }
}